#include "textures.h"

#include "helpers/glbuffers.h"

#include <QHash>
#include <QSharedPointer>
#include "common.h"

namespace Opl{ namespace Gui {


class TexturesPrivate{
	public:
	TexturesPrivate():
			current(0)
	{}
		~TexturesPrivate()
		{
			current = 0;
			QHashIterator<int, Helpers::OpenGL::GLTexture*> i(textures);
			 while (i.hasNext()) {
				 i.next();
				 //LT << "Delete Texture:" << i.key();
				 delete i.value();
			 }
		}
		QHash<int, Helpers::OpenGL::GLTexture*> textures;
		Helpers::OpenGL::GLTexture* current;
};

Textures* Textures::instance()
{
    static QSharedPointer<Textures> _t(new Textures);
    return _t.data();
}

Textures::Textures(QObject *parent) :
    QObject(parent), O_PRIVATE_CREATE(Textures)
{
    O_D(Textures);
}

Textures::~Textures()
{

	O_PRIVATE_DELETE;
}

int Textures::size()const
{
	O_C(Textures);
	d->textures.size();
}

bool Textures::append(int id, Helpers::OpenGL::GLTexture* item)
{
	O_D(Textures);
	//LIT << "Append Texture:" << id;
	if (!d->textures.contains(id) && item && !item->failed()){
		d->textures.insert(id, item);
		return true;
	}

	return false;
}

bool Textures::append(int id, const QImage& image)
{
	return append(id, new Helpers::OpenGL::GLTexture2D(image));
}

bool Textures::append(int id, const QString& fileName)
{
	return append(id, QImage(fileName));
}

void Textures::bind(int id)
{
	O_D(Textures);
	d->current = d->textures.value(id, 0);
	bind();
}

void Textures::bind()
{
	O_D(Textures);
	if (d->current == 0)
		return;

	d->current->bind();
}

void Textures::unbind()
{
	O_D(Textures);
	if (d->current == 0)
		return;

	d->current->unbind();
}

};};
